package com.aquan.map_jetpack.viewmodel

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aquan.map_jetpack.model.entity.UserInfoEntity
import com.aquan.map_jetpack.model.managers.UserInfoManager
import com.aquan.map_jetpack.model.service.LoginService
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch

class UserViewModel(context: Context) : ViewModel() {
    // TODO 调用了数据的缓存
    private val userInfoManager = UserInfoManager(context)

    private val loginService = LoginService.instance()


    var userInfo: UserInfoEntity? = null
        private set

    init {
        viewModelScope.launch {
            val userName = userInfoManager.userName.firstOrNull()
            userInfo = if (userName?.isNotEmpty() == true) {
                UserInfoEntity(userName)
            } else {
                null
            }
        }
    }

    val logged: Boolean
        get() {
            return userInfo != null
        }

    // 用户登录 协程
    suspend fun login(
        context: Context,
        userName: String = "",
        password: String = "",
        onClose: () -> Unit = {}
    ) {
        try {
            val res = loginService.login(pwd = password, name = userName)
            Log.i("aquan", res.toString())
            if (res.code == "1") {
                Log.i("用户登录", "用户登录")
                //TODO 用户登录
                userInfo = UserInfoEntity("1")
                userInfoManager.save("1")
                onClose()
            } else {
                Log.i("用户登录", "登录失败")
            }
        } catch (e: Exception) {
            Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show()
        }
    }

    fun clear() {
        viewModelScope.launch {
            userInfoManager.clearUserName()
        }
    }

}